package cn.bs.ktv.view;

import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;

import cn.bs.ktv.R;
import cn.bs.ktv.connection.ConnectionMgr;
import cn.bs.ktv.model.Constant;
import cn.bs.ktv.util.IntegerUtil;

public class ConnectActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_connect);

        registerClickEvent();
    }

    private void registerClickEvent() {
        Button btn_cancel = findViewById(R.id.btn_cancel);
        btn_cancel.setOnClickListener(view -> finish());

        Button btn_connect = findViewById(R.id.btn_connect);
        btn_connect.setOnClickListener(view -> {
            EditText et_ip = findViewById(R.id.et_ip);
            EditText et_port = findViewById(R.id.et_port);

            String ip = et_ip.getText().toString();
            int port = IntegerUtil.parseInt(et_port.getText().toString());

            if (StringUtils.isEmpty(ip)) {
                ToastUtils.showLong(R.string.tip_input_ip);
                return;
            }

            if (port < 1 || port > 65536) {
                ToastUtils.showLong(R.string.tip_input_port);
                return;
            }

            ConnectionMgr.connect(ip, port, s -> {
                if (s.equals(Constant.CONNECTION_SUCCESS)) {
                    ToastUtils.showLong(R.string.tip_connection_success);
                    finish();
                } else {
                    ToastUtils.showLong(R.string.tip_connection_error);
                }
            });
        });
    }
}